package com.htyz.controller;

import com.alibaba.fastjson.JSON;
import com.htyz.entity.ScenicSpots;
import com.htyz.mapper.ChartsMapper;
import com.htyz.mapper.ScenicSpotsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("introduction")
public class IntroductionController {
    @Autowired
    private ChartsMapper chartsMP;

    @Autowired
    private ScenicSpotsMapper scenicSpotsMapper;
    private static List<ScenicSpots> list = new ArrayList<>();

    static {
        for (int i = 0; i < 120; i++) {
            ScenicSpots introduction = new ScenicSpots();
            introduction.setId(i + 1);
            //本机的host + 本机的port
            introduction.setImage("image" + (i + 1)  + ".jpg");
            list.add(introduction);
        }

    }



    @GetMapping("list")
    public String getList(HttpServletRequest request){
        String host = request.getServerName();
        int port = request.getServerPort();
        String protocol = request.getProtocol();
        System.out.println(request.getRequestURL());
        String p = request.getRequestURL().toString().split("://")[0];
        String preUrl = p + "://" + host +":" + port +"/images/";
        List<ScenicSpots> ScenicSpots=scenicSpotsMapper.selectList(null);


        for(ScenicSpots i : ScenicSpots){
            if(!i.getImage().startsWith( p )){
                i.setImage( preUrl + i.getImage());
            }
        }
        return JSON.toJSONString(ScenicSpots);
        //返回数据
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable("id") Integer id, HttpServletRequest request){
        String host = request.getServerName();
        int port = request.getServerPort();
        String p = request.getRequestURL().toString().split("://")[0];
        String preUrl = p + "://" + host +":" + port +"/images/";
        List<ScenicSpots> ScenicSpots=scenicSpotsMapper.selectList(null);
        for(ScenicSpots i : ScenicSpots){
            if(!i.getImage().startsWith( p )){
                i.setImage( preUrl + i.getImage());
            }
        }
        //找到id
        try{
            int i = id - 1;
            ScenicSpots introduction = ScenicSpots.get( i );
            introduction.setHeaderImage(preUrl + "tx" + id +".jpg");
            return JSON.toJSONString( introduction );
        }catch (Exception e){
            return "error";
        }

    }

    @GetMapping("/chartsList")
    public String chartsList(HttpServletRequest request){
        return JSON.toJSONString(chartsMP.selectList(null));
    }
}
